<template>
  <a-modal
    :title='title'
    :width='800'
    :visible='visible'
    :confirmLoading='confirmLoading'
    switchFullscreen
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'>

    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>

        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='访客姓名'>
          <a-input placeholder='请输入访客姓名' v-decorator="['visitName', validatorRules.visitName ]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='身份证号码'>
          <a-input placeholder='请输入身份证号' v-decorator="['cardNum', {rules:[{required:true,message:'请输入身份证号'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='访客手机号'>
          <a-input placeholder='请输入访客手机号' v-decorator="['visitMobile', {}]" />
        </a-form-item>
        <a-form-item :labelCol='labelCol'
                     :wrapperCol='wrapperCol' label='项目'>
          <a-select :show-search='showSearch' placeholder='请输入项目' :filter-option='filterOption' label-in-value
                    style='width: 200px;margin-right: 20px'
                    v-decorator="['projectId',{rules:[{required:true,message:'请选择项目！'}]}]" @change='initUserList'
                    :options='projectList'>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol='labelCol'
                     :wrapperCol='wrapperCol' label='户主姓名'>
          <a-select :show-search='showSearch' placeholder='户主姓名' :filter-option='filterOption' label-in-value
                    style='width: 200px;margin-right: 20px'
                    v-decorator="['userId',{rules:[{required:true,message:'请选择访问户主！'}]}]" @change='initHouseList'
                    :options='userList'>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol='labelCol'
                     :wrapperCol='wrapperCol' label='被访房屋'>
          <a-select :show-search='showSearch' placeholder='被访房屋' :filter-option='filterOption' label-in-value
                    style='width: 400px;margin-right: 20px'
                    v-decorator="['houseId',{rules:[{required:true,message:'请选择房屋位置！'}]}]"
                    :options='houseList'>
          </a-select>
        </a-form-item>
        <a-form-item
          v-show='false'
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='登记类型'>
          <a-input placeholder='请输入登记类型(1-微信小程序2-线下等级)' v-decorator="['registerType', {initialValue:1}]" />
        </a-form-item>
        <a-form-item
          v-show='false'
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='来访类型'>
          <a-input placeholder='请输入来访类型(1-业主邀请2-亲友来访)' v-decorator="['sourceType', {initialValue:1}]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='访客车牌号'>
          <a-input placeholder='请输入访客车牌号' v-decorator="['visitVehicleNo', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='随行人数'>
          <a-input-number v-decorator="[ 'visitPeopleNum', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='备注'>
          <a-input placeholder='请输入备注' v-decorator="['remark', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='到访开始时间'>
          <a-date-picker showTime format='YYYY-MM-DD HH:mm:ss' v-decorator="[ 'startTime',{rules:[{required:true,message:'请选择到访结束时间'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='到访结束时间'>
          <a-date-picker showTime format='YYYY-MM-DD HH:mm:ss' v-decorator="[ 'endTime', {rules:[{required:true,message:'请选择到访结束时间'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='逾期是否允许进入'>
          <a-radio-group buttonStyle="solid" v-decorator="[ 'overdue', {initialValue:0}]">
            <a-radio-button :value='0'>是</a-radio-button>
            <a-radio-button :value='1'>否</a-radio-button>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import { getProjectList } from '@api/api'

export default {
  name: 'VisitorModal',
  data() {
    return {
      showSearch:true,
      projectList:[],
      userList:[],
      houseList:[],
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        visitName: { rules: [{ required: true, message: '请输入访客姓名!' }] },
        projectId: { rules: [{ required: true, message: '请输入项目id!' }] }
      },
      url: {
        add: '/visitor/add',
        edit: '/visitor/edit',
        getUserList:'/user/user/getUserByProjectId',
        getHouseList:'/house/getHouseByOwnerUser'
      }
    }
  },
  created() {
    this.initProjectList()
  },
  methods: {
    initProjectList() {
      getProjectList().then((res) => {
        this.projectList = []
        if (res.success) {
          if (res.result !== null) {
            res.result.forEach(item => {
              this.projectList.push({
                value: item.id,
                key: item.id,
                label: item.name
              })
            })
          }
        }
      })
    },
    filterOption(input, option) {
      let com = option.componentOptions
      let name = String(com.propsData.label)
      if (name.toLowerCase().includes(input.toLowerCase())) {
        return true
      }
    },

    add() {
      this.edit({})
    },
    edit(record) {
      console.log("@@@",record)
      this.form.resetFields()
      this.visible = true
      if (record.id!=null){
        this.model = Object.assign({}, record)
        this.loadUserAndHouse()
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'visitName', 'visitMobile', 'registerType', 'sourceType', 'cardNum','visitVehicleNo', 'visitPeopleNum',  'remark', 'overdue'))
          //时间格式化
          this.form.setFieldsValue({ startTime: this.model.startTime ? moment(this.model.startTime) : null })
          this.form.setFieldsValue({ endTime: this.model.endTime ? moment(this.model.endTime) : null })
        })
      }

    },
    async loadUserAndHouse(){
     await this.getUserList(this.model.projectId)
     await  this.getHouseList(this.model.userId)
      this.$nextTick(() => {
        let project = this.projectList.find(item => {
          if (item.key === this.model.projectId) {
            return true
          }
        })
        this.form.setFieldsValue({ projectId: project })
        let user = this.userList.find(item => {
          if (item.key === this.model.userId) {
            return true
          }
        })
        this.form.setFieldsValue({ userId: user })
        let house = this.houseList.find(item => {
          if (item.key === this.model.visitHouseId) {
            return true
          }
        })
        this.form.setFieldsValue({ houseId: house })
      })
    },
    initUserList(e) {
      this.form.resetFields(['userId', 'houseId'])
      this.userList = []
      this.houseList = []
      this.getUserList(e.key)
    },
    async getUserList(id){
      await getAction(this.url.getUserList,{id:id}).then((res)=>{
        if (res.success){
          if (res.result!=null){
            console.log(res.result)
            res.result.forEach((item)=>{
              this.userList.push({
                key:item.id,
                value:item.id,
                label:item.userName
              })
            })
            console.log("@@",res.result)
          }
        }
      })
    },
    initHouseList(e){
      this.form.resetFields(['houseId'])
      this.houseList=[]
      this.getHouseList(e.key)
    },
    async getHouseList(id){
      await getAction(this.url.getHouseList,{id:id}).then((res)=>{
        if (res.success){
          if (res.result!=null){
            console.log(res.result)
            res.result.forEach(item=>{
              this.houseList.push({
                value:item.id,
                key:item.id,
                label:item.locateName
              })
            })
          }
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          //时间格式化
          formData.startTime = formData.startTime ? formData.startTime.format('YYYY-MM-DD HH:mm:ss') : null
          formData.endTime = formData.endTime ? formData.endTime.format('YYYY-MM-DD HH:mm:ss') : null

          console.log(formData)
          if (formData.houseId!=null){
            formData.visitHouseId = formData.houseId.key
          }
          if (formData.projectId!=null){
            formData.projectId = formData.projectId.key
          }
          if (formData.userId!=null){
            formData.userId = formData.userId.key
          }
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })


        }
      })
    },
    handleCancel() {
      this.close()
    }


  }
}
</script>

<style lang='less' scoped>

</style>